<template>

  <div class="bigbox">
    <div class="tiwen" @click="opentiwen">我要提问</div>
    <textarea v-if="iftiwen" class="question-box" rows="4" cols="50" v-model="input0"></textarea>
    <div v-if="iftiwen" class="submit" @click="submittoproblem">发表</div>
  </div>

  <div class="userproblem" v-for="(ProblemItem, index) in datas" :key="index">
    <div class="problemhang">
      <p>问题{{ProblemItem.ProblemId}}: {{ ProblemItem.Problem }}</p>
      <div class="reply" @click="toggleAnswerInput(ProblemItem.ProblemId)">回复</div>
    </div>


    <div class="submithang" v-if="showAnswerInput[ProblemItem.ProblemId]">
      <input type="text" v-model="answers[ProblemItem.ProblemId]">
      <div class="submit" @click="submittoanswer(ProblemItem.ProblemId)">发表</div>
    </div>

    <div class="answerhang" v-for="(filteredAnswer, index2) in renderAnswers(ProblemItem.ProblemId)"
      :key="filteredAnswer.AnswerId">
      <p>回答: {{ filteredAnswer.Answer }}</p>
    </div>
    <p>
      --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    </p>
  </div>

</template>

<script setup>
  import { ref, onMounted } from 'vue';

  const prourl = 'http://119.28.50.240:8080/api/problemdata';
  const ansurl = 'http://119.28.50.240:8080/api/answerdata';
  const datas = ref([]); // 使用 ref 来创建一个响应式的数组，用于存储 Answers  
  const answerdatas = ref([]);
  const input0 = ref(''); // ProblemId  
  const inputValue = ref('');
  const inputValue2 = ref('');
  const ifcome = ref(false);
  const iftiwen = ref(false);

  const showAnswerInput = ref({}); // 初始化为一个空对象，用于存储每个问题的显示状态  
  const answers = ref({}); // 初始化为一个空对象，用于存储每个问题的回答文本  

  function toggleAnswerInput(problemId) {
    // 切换特定问题的显示状态  
    showAnswerInput.value[problemId] = !showAnswerInput.value[problemId];
    // 如果之前没有为该问题设置过回答文本，则初始化一个空字符串  
    if (!answers.value[problemId]) {
      answers.value[problemId] = '';
    }
  }

  const submittoproblem = async () => {
    try {
      // 准备要发送的数据  
      const formData = {
        Problem: input0.value
      };

      // 发送 POST 请求到后端 API  
      const response = await fetch('http://119.28.50.240:8080/api/problemdata', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
      });

      // 检查响应  
      if (!response.ok) {
        throw new Error('Failed to submit data');
      }

      // 处理成功的响应（比如刷新 answers 列表，但这取决于你的后端逻辑）  
      const data = await response.json();
      console.log('Data submitted successfully:', data);

      // 如果需要的话，重置输入框  
      input0.value = '';

    } catch (error) {
      console.error('Error submitting data:', error);
    }
  };

  const submittoanswer = async (problemid) => {
    try {
      // 准备要发送的数据  
      const formData = {
        ProblemId: problemid,
        Answer: answers.value[problemid]
      };

      // 发送 POST 请求到后端 API  
      const response = await fetch('http://119.28.50.240:8080/api/answerdata', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
      });

      // 检查响应  
      if (!response.ok) {
        throw new Error('Failed to submit data');
      }

      // 处理成功的响应（比如刷新 answers 列表，但这取决于你的后端逻辑）  
      const data = await response.json();
      console.log('Data submitted successfully:', data);

      // 如果需要的话，重置输入框  
      answers.value[problemid] = '';

    } catch (error) {
      console.error('Error submitting data:', error);
    }
  };

  onMounted(async () => {
    try {
      const response = await fetch(prourl); // 使用 fetch 替代 XMLHttpRequest  
      const response2 = await fetch(ansurl); // 使用 fetch 替代 XMLHttpRequest  
      if (!response.ok || !response2.ok) {
        throw new Error('Failed to fetch data');
      }
      const data = await response.json();
      const answerdata = await response2.json();
      if ((data.code === 200 && data.data) && (answerdata.code === 200 && answerdata.data)) {
        datas.value = data.data; // 将获取到的 Answers 数组赋值给 answers  
        answerdatas.value = answerdata.data; // 将获取到的 Answers 数组赋值给 answers  
      } else {
        console.error('获取数据失败', data.message);
      }
    } catch (error) {
      console.error('发生错误:', error);
    }
  });

  function renderAnswers(problemId) {
    return answerdatas.value.filter(answerItem => answerItem.ProblemId === problemId);
  }
  function opencome() {
    ifcome.value = true;
  }
  function opentiwen() {
    iftiwen.value = !iftiwen.value;
  }
</script>



<style>
  /* .bigbox {
    display: flex;
    margin: 70px 0;
    height: 100px;
    border: 1px red solid;
  } */
  .bigbox {
    display: flex;
    justify-content: space-between;
    /* 在主轴上均匀分配剩余空间 */
    align-items: center;
    margin: 60px 0;
    height: 120px;
    /* border: 1px red solid;   */
    padding: 0 8%;
    /* 为内容添加内边距以防止靠边 */
  }

  .tiwen {
    /* margin-left: 180px; */
    height: 55px;
    line-height: 55px;
    text-align: center;
    /* border: 1px red solid; */
    flex: 0 0 8%;
    background-color: rgb(120, 175, 249);
    color: white;
    border-radius: 10%;
    cursor: pointer;
  }

  .question-box {
    flex: 0 0 75%;
    height: 100px;
    /* margin: 0 15px; */
    padding: 0 10px;
    /* padding-bottom: 50px; */
  }

  .submit {
    /* border: 1px red solid; */
    height: 55px;
    text-align: center;
    width: 6%;
    line-height: 55px;
    background-color: rgb(120, 175, 249);
    color: white;
    border-radius: 10%;
    cursor: pointer;
    /* flex:1 */
  }

  .reply {
    /* flex: 0 0 10; */
    width: 6%;
    line-height: 40px;
    height: 40px;
    text-align: center;
    background-color: rgb(120, 175, 249);
    color: white;
    border-radius: 10%;
    cursor: pointer;
  }

  .problemhang {
    display: flex;
  }

  .problemhang p {
    flex: 0 0 80.7%;
  }

  .submithang {
    display: flex;
  }

  .submithang input {
    flex: 0 0 80%
  }

  .userproblem {
    margin: 0 8%;
  }

  .answerhang {
    margin: 0 30px;
  }
</style>